package com.free.company.member.service;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.free.beanutils.BeanUtils;
import com.free.company.member.constants.SysContants;
import com.free.company.member.logic.AuthInfoLogic;
import com.free.company.member.model.User;
import com.free.ext.logger.FreeLogger;
import com.free.ext.logger.FreeLoggerFactory;
import com.free.ext.wechat.qy.QyWxProxy;
import com.free.utils.UrlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 功能概述:
 * </p>
 * <p>
 * 功能详述:
 * </p>
 */
@Service
public class AuthInfoService extends CommonService{
    /*========================================================================*
     *                         Public Fields (公共属性)
     *========================================================================*/

    /*========================================================================*
     *                         Private Fields (私有属性)
     *========================================================================*/

    @Autowired
    private AuthInfoLogic logic;

    private static final FreeLogger LOGGER = FreeLoggerFactory.getLogger(AuthInfoService.class);

    /*========================================================================*
     *                         Construct Methods (构造方法)
     *========================================================================*/

    /*========================================================================*
     *                         Public Methods (公有方法)
     *========================================================================*/

    public String authInfo(String code, String appid, String extattr, String url){
        LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{}",code,appid,extattr,url);
        if(StringUtils.isEmpty(code)){
            return "";
        }
        QyWxProxy proxy = getProxy(appid);
        if(proxy == null){
            return "";
        }
        LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},准确的拿到了代理",code,appid,extattr,url);
        try {

            com.foxinmy.weixin4j.qy.model.User user = proxy.getUserByCode(code);
            String userId = user.getUserId();
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},微信的openid:{}",code,appid,extattr,url,userId);
            User userInfo = logic.getUserInfo(userId);
            if(userInfo == null){
                return "";
            }
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},获得的用户信息",code,appid,extattr,url,userInfo.toString());
            String res = combineInfo(userInfo,extattr,url);
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},最终返回{}",code,appid,extattr,url,res);
            return res;
        } catch (WeixinException e) {
            LOGGER.info("AuthInfoService.authInfo 发生异常", e);
            return "";
        }
    }

    public Map<String,String> authInfoParams(String code, String appid, String extattr, String url){
        Map<String,String> redirectParams = new HashMap<>();
        LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{}",code,appid,extattr,url);
        if(StringUtils.isEmpty(code)){
            return redirectParams;
        }
        QyWxProxy proxy = getProxy(appid);
        if(proxy == null){
            return redirectParams;
        }
        LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},准确的拿到了代理",code,appid,extattr,url);
        try {
            com.foxinmy.weixin4j.qy.model.User user = proxy.getUserByCode(code);
            String userId = user.getUserId();
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},微信的openid:{}",code,appid,extattr,url,userId);
            User userInfo = logic.getUserInfo(userId);
            if(userInfo == null){
                return redirectParams;
            }
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},获得的用户信息",code,appid,extattr,url,userInfo.toString());
            redirectParams = paramsMap(userInfo,extattr);
            LOGGER.info("拿到code:{},appid:{},extattr:{},jumpUrl:{},最终返回{}",code,appid,extattr,url,redirectParams);
            return redirectParams;
        } catch (Exception e) {
            LOGGER.info("AuthInfoService.authInfo 发生异常", e);
            return redirectParams;
        }
    }

    public String getRedirectUrl(String appId, String extattr, String url){
        QyWxProxy proxy = getProxy(appId);
        String redirecturl = getUrl(appId, extattr, url);
        String poxyUrl = proxy.getOauthApi().getUserAuthorizationURL(redirecturl,"snsapi_base", "state", null);
        return poxyUrl;
    }

    private String getUrl(String appid, String extattr, String url){
        String redirecturl = SysContants.instance().getAuthinfoUrl()+"?appid=" + appid +"&extattr=" + extattr
                +"&url="+url;
        return UrlUtils.decode(redirecturl);
    }

    private Map<String,String> paramsMap(User user, String extattr){
        Map<String,String> paramsMap = new HashMap<>();
        String[] attrs = extattr.split(",");
        if(attrs != null && attrs.length > 0 ){
            Arrays.asList(attrs).forEach(x->{
                try {
                    String val = BeanUtils.getProperty(user,x);
                    paramsMap.put(x,isEmptyToDefault(val,""));
                } catch (Throwable e) {
                    LOGGER.info("AuthInfoService.combineInfo 发生异常", e);
                }
            });
        }
        paramsMap.put("userid",user.getUserid());
        paramsMap.put("sgmjxsver",randomId());
        return paramsMap;
    }

    private String combineInfo(User user, String extattr, String url){
        String[] attrs = extattr.split(",");
        if(attrs == null || attrs.length == 0 ){
            return url;
        }
        List<String> res = new ArrayList<>();
        Arrays.asList(attrs).forEach(x->{
            try {
                String val = BeanUtils.getProperty(user,x);
                res.add(x + "=" + isEmptyToDefault(val, ""));
            } catch (Throwable e) {
                LOGGER.info("AuthInfoService.combineInfo 发生异常", e);
            }
        });
        String connetTg = "?";
        if(url.indexOf("?")>=0){
            connetTg = "&";
        }
       String redirectUrl = url + connetTg + org.apache.commons.lang3.StringUtils.join(res,"&") + "&userid=" + user.getUserid();
       return redirectUrl;
    }

    /*========================================================================*
     *                         Private Methods (私有方法)
     *========================================================================*/

    private String isEmptyToDefault(String str, String defaultStr){
        String val = org.apache.commons.lang3.StringUtils.isEmpty(str)?defaultStr:str;
        return UrlUtils.encode(val);
    }

    private String randomId(){
        return UUID.randomUUID().toString().replace("-","");
    }

}
